package com.mall.b2c.hessian;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.mall.b2c.Setting;
import com.mall.b2c.bean.AdvertBean;
import com.mall.b2c.bean.ArticleBean;
import com.mall.b2c.bean.ArticleCategoryBean;
import com.mall.b2c.bean.GoodsCategoryBean;

@Service
public class CacheService {
	
	@Resource private SystemHessian systemHessian;
	@Resource private GoodsHessian goodsHessian;
	@Resource private ContentHessian contentHessian;
	
	/**
	 * 将json转换成对象
	 * @param json json值
	 * @param clazz 转换的类型
	 * @return
	 */
	private <T> T jsonToObj(String json, Class<T> clazz){
		return JSONObject.parseObject(json, clazz);
	}
	
	/**
	 * 将json转换成list
	 * @param json json值
	 * @param clazz 转换的类型
	 * @return
	 */
	private <T> List<T> jsonToList(String json, Class<T> clazz){
		return JSONObject.parseArray(json, clazz);
	}

	@Cacheable(value="setting",key="'b2c'")
	public Setting getSystemConfig(){
		return jsonToObj(systemHessian.getSetting(), Setting.class);
	}
	
	@Cacheable(value="b2cGoodsCategory" ,key="#goodsCategoryIds+','+#isVisible+','+#parentId+','+#isRecommend+','+#count+',priority asc'")
	public List<GoodsCategoryBean> getList(Long[] goodsCategoryIds, Long parentId,
			Boolean isRecommend, Boolean isVisible, Integer count) {
		if(goodsCategoryIds!=null && goodsCategoryIds.length>0){
			return jsonToList(goodsHessian.getGoodsCategoryList(
					goodsCategoryIds, null, null, null, null, "priority asc"),
					GoodsCategoryBean.class);
		}else{
			return jsonToList(goodsHessian.getGoodsCategoryList(
					null, isVisible, parentId, isRecommend, count, "priority asc"), 
					GoodsCategoryBean.class);
		}
	}
	
	@Cacheable(value="area", key="'area'+#parentId")
	public String getAreaByParentId(Long parentId){
		return systemHessian.getAreaByParentId(parentId);
	}

	@Cacheable(value="adPosition", key="'advert'+#position+','+#num")
	public List<AdvertBean> getAdverts(String position, Integer num) {
		return jsonToList(contentHessian.getAdvertBeans(position, num), AdvertBean.class);
	}	
	
	@Cacheable(value="article", key="'article'+#catId+','+#isPublication+','+#isRecommend+','+#isTop+','+#orderBy+','+#count+','+#categoryCode")
	public List<ArticleBean> getAticles(Long catId, Boolean isPublication,
			Boolean isRecommend, Boolean isTop, String orderBy , Integer count, String categoryCode) {
		return jsonToList(contentHessian.getArticleBeans(catId, categoryCode, isPublication, isTop, isRecommend, orderBy, count), ArticleBean.class);
	}

	@Cacheable(value="articleCategory", key="'articleCategory'+#parentCode+','+#count")
	public List<ArticleCategoryBean> getArticleCategory(String parentCode, Integer count) {
		return jsonToList(contentHessian.getArticlecategoryBeans(parentCode, count), ArticleCategoryBean.class);
	}
}
